package com.common.www.controller.project;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.common.www.aop.resolver.CurrentUser;
import org.springframework.boot.base.jpa.service.IBaseService;
import com.common.www.bean.entity.Result;
import com.common.www.bean.entity.auth.AuthUser;
import com.common.www.bean.entity.programme.BasisDemand;
import com.common.www.bean.entity.programme.ComparativeAnalysisRemark;
import com.common.www.bean.entity.project.GdyBasic;
import com.common.www.bean.entity.project.Project;
import com.common.www.bean.entity.project.XfgcBasic;
import com.common.www.bean.vo.UserVo;
import com.common.www.controller.base.DefaultCrudController;
import com.common.www.data.NetCode;
import com.common.www.service.auth.UserService;
import com.common.www.service.programme.BasisDemandService;
import com.common.www.service.project.GdyBasicService;
import com.common.www.service.project.ProjectService;
import com.common.www.service.project.XfgcBasicService;
import com.common.www.utils.FormatUtils;
import com.common.www.utils.ParamsUtils;
import com.common.www.utils.R;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.util.LinkedHashMap;
import java.util.List;


@CrossOrigin
@RestController
@RequestMapping(value = {"mgt/project"})
@Api(tags = "MGT 项目基本信息管理接口")
public class MGTProjectController extends DefaultCrudController<Project, Long> {
    @Autowired
    private ProjectService service;
    @Autowired
    private BasisDemandService basisDemandService;
    @Autowired
    private GdyBasicService gdyBasicService;
    @Autowired
    private XfgcBasicService xfgcBasicService;
    @Autowired
    private UserService userService;

    protected IBaseService getService() {
        return service;
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "json", value = "String", defaultValue = ""),
    })
    @RequestMapping(value = "/saveByJson", method = RequestMethod.POST)
    public Result saveByJson(String json,@CurrentUser UserVo userVo) {
        boolean isAdd=false;
        boolean addMark=false;
        if(!userVo.getAccessList().contains("superManager")){
            AuthUser authUser = userService.getById(userVo.getId());
            if(userVo.getAccessList().contains("高低压配电")){
                if(!StringUtils.isBlank(authUser.getProjectIds())){
                    addMark = true;
                }
            }
        }
        Project parsedProject = JSON.parseObject(json, Project.class);
        if (parsedProject.getId() == null) {
            isAdd=true;
            service.saveAndFlush(parsedProject);
        } else {
            // 如果 id 不为空，则从数据库中获取现有对象
            Project existingProject = service.getByIdLogic(parsedProject.getId());
            if (existingProject != null) {
                // 如果存在，则更新现有对象的属性
                BeanUtils.copyProperties(parsedProject, existingProject, "id");
                // 然后保存更新后的对象
                service.saveAndFlush(existingProject);
            } else {
                // 如果不存在，则保存解析出来的对象
                service.saveAndFlush(parsedProject);
            }
        }
        //查询基础用需表，存在则不变，不存在则添加
        BasisDemand basisDemand = basisDemandService.getRepository().findByFlagAndProjectId(1,parsedProject.getId());
        if (basisDemand == null || basisDemand.getId() == null){
            basisDemand = new BasisDemand();
            basisDemand.setProject(parsedProject);
            basisDemandService.save(basisDemand);
        }
        //新增项目将项目id追加到该用户后面
        if(isAdd && addMark){
            AuthUser authUser = userService.getById(userVo.getId());
            if(authUser.getProjectIds()!=null&&authUser.getProjectIds().length()>0){
                authUser.setProjectIds(authUser.getProjectIds()+","+parsedProject.getId());
            }else{
                authUser.setProjectIds(String.valueOf(parsedProject.getId()));
            }
            userService.save(authUser);
        }
        return R.ok(parsedProject);
    }


    @ApiOperation("批量删除启用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "String", defaultValue = ""),
            @ApiImplicitParam(name = "operate", value = "1.删除 2.启用", defaultValue = ""),
    })
    @RequestMapping(value = "/batchDelete", method = RequestMethod.POST)
    public Result batchDelete(Long[] ids, Integer operate) {
        if (ParamsUtils.isInputEmpty(ids, operate)) {
            return R.returnCode(NetCode.CODE_INPUT_OMIT);
        }
        for (int i = 0; i < ids.length; i++) {
            Project project = service.findOne(ids[i]);
            if(project!=null){
                project.setFlag(0);
                service.save(project);
                //删除首页对应项目的高低压基础用需信息
                BasisDemand basisDemand = basisDemandService.getRepository().findByFlagAndProjectId(1,project.getId());
                if (basisDemand != null){
                    basisDemandService.delete(basisDemand);
                }
                //删除高低压和消防工程基础配置信息
                GdyBasic gdyBasic = gdyBasicService.getRepository().findByFlagAndProjectId(1,project.getId());
                XfgcBasic xfgcBasic = xfgcBasicService.getRepository().findByFlagAndProjectId(1,project.getId());
                if (gdyBasic != null){
                    gdyBasicService.delete(gdyBasic);
                }
                if (xfgcBasic != null){
                    xfgcBasicService.delete(xfgcBasic);
                }
            }
        }
        return R.ok();
    }


    @ApiOperation(value = "逻辑删除", notes = "参数为JSON数据对象")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", dataType = "long", paramType = "query"),
    })
    @RequestMapping(value = "/deleteByLogic", method = RequestMethod.POST)
    public Result deleteByLogic(Long id) {
        service.delete(id);
        return R.ok();
    }

    @ApiOperation(value = "逻辑删除批量", notes = "参数为JSON数据对象")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "8,28", dataType = "long", paramType = "query"),
    })
    @RequestMapping(value = "/deletesByLogic", method = RequestMethod.POST)
    public Result deletesByLogic(Long[] ids) {
        service.delete(ids);
        return R.ok();
    }


    @ApiOperation(value = "消防工程-查询项目列表数据", nickname = "", notes = "")
    @ApiImplicitParams(value = {
    })
    @RequestMapping(value = "/getProjectXfgcList", produces = {"application/json"}, method = RequestMethod.POST)
    public Result getProjectXfgcList(String params, Integer page, Integer size, String sortJsonStr, @CurrentUser UserVo userVo) {
        LinkedHashMap<String, Object> hashMap = (LinkedHashMap<String, Object>)
                JSON.parseObject(params, new TypeReference<LinkedHashMap<String, Object>>() {
                });
        if (hashMap == null) hashMap = new LinkedHashMap<>();
        hashMap.put("flag",1);
        if(!userVo.getAccessList().contains("superManager")){//如果并非是管理员  动态修改权限后  需要重新登录才生效
            AuthUser authUser = userService.getById(userVo.getId());
            if(userVo.getAccessList().contains("消防工程")){
                if(!StringUtils.isBlank(authUser.getProjectIds())){//新建用户为空的情况
                    hashMap.put("id_in", FormatUtils.getFormatList(authUser.getProjectIds(), ","));
                }
            }else{
                hashMap.put("id", 0);
            }
        }
        Result<List<Project>> result = this.query(JSONObject.toJSONString(hashMap),  page,  size, sortJsonStr);

//        Result<List<Project>> result = super.query(params, page, size, sortJsonStr);
        List<Project> list = result.getData();
        GdyBasic gdyBasic = new GdyBasic();
        XfgcBasic xfgcBasic = new XfgcBasic();
        for (Project p : list){
            gdyBasic = gdyBasicService.getRepository().findByFlagAndProjectId(1,p.getId());
            xfgcBasic = xfgcBasicService.getRepository().findByFlagAndProjectId(1,p.getId());
            p.setGdyBasic(gdyBasic);
            p.setXfgcBasic(xfgcBasic);
        }
        Result result1 = new Result();
        result1.setData(list);
        result1.setCode(result.getCode());
        result1.setMessage(result.getMessage());
        result1.setPage(result.getPage());
        result1.setTotalElements(result.getTotalElements());
        result1.setTotalPage(result.getTotalPage());
        result1.setException(result.exception);
        return result1;
    }



    @ApiImplicitParams({
            @ApiImplicitParam(name = "params", value = "params", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "pageable", value = "pageable", dataType = "string", paramType = "query"),
    })
    @ApiOperation(value = "消防工程-查询项目列表数据", notes = "返回数据中的data为一个数据列表<br/>此函数有2组参数，第一组是查询参数，以params开头，第二组为分页参数，以pageable开头<br/>参数示例如下（支持form data或queryString），<br/>\n" +
            "&nbsp;&nbsp;&nbsp;&nbsp;params.username_eq:maomao(表示username等于maomao,eq表示等于)<br/>\n" +
            "&nbsp;&nbsp;&nbsp;&nbsp;params.age_gt:10(表示age大于10，gt表示大于，ge为大于等于，le为小于等于，lt为小于)<br/>\n" +
            "&nbsp;&nbsp;&nbsp;&nbsp;params.xxx_like:val%(表示用某个属性做LIKE比较,比较值为val%，另外支持notlike)<br/>\n" +
            "&nbsp;&nbsp;&nbsp;&nbsp;pageable.page:0(当前页)<br/>\n" +
            "&nbsp;&nbsp;&nbsp;&nbsp;pageable.start:0(起始记录)<br/>\n" +
            "&nbsp;&nbsp;&nbsp;&nbsp;pageable.size:25(共取多少条数据)<br/>\n" +
            "&nbsp;&nbsp;&nbsp;&nbsp;pageable.sort:【{\"property\":\"cdt\",\"direction\":\"ASC\"}】(用cdt降序排序，支持多组排序)")
    @RequestMapping(value = "/getProjectGdyList", method = RequestMethod.POST)
    public Result<List<Project>> getProjectGdyList(String params, Integer page, Integer size, String sortJsonStr, @CurrentUser UserVo userVo) {
        LinkedHashMap<String, Object> hashMap = (LinkedHashMap<String, Object>)
                JSON.parseObject(params, new TypeReference<LinkedHashMap<String, Object>>() {
                });
        if (hashMap == null) hashMap = new LinkedHashMap<>();
        hashMap.put("flag",1);
        if(!userVo.getAccessList().contains("superManager")){//如果并非是管理员  动态修改权限后  需要重新登录才生效
            AuthUser authUser = userService.getById(userVo.getId());
            if(userVo.getAccessList().contains("高低压配电")){
                if(!StringUtils.isBlank(authUser.getProjectIds())){//新建用户为空的情况
                    hashMap.put("id_in", FormatUtils.getFormatList(authUser.getProjectIds(), ","));
                }
            }else{
                hashMap.put("id", 0);
            }
        }

        Result<List<Project>> result = this.query(JSONObject.toJSONString(hashMap),  page,  size, sortJsonStr);
        List<Project> list = result.getData();
        GdyBasic gdyBasic = new GdyBasic();
        XfgcBasic xfgcBasic = new XfgcBasic();
        for (Project p : list){
            gdyBasic = gdyBasicService.getRepository().findByFlagAndProjectId(1,p.getId());
            xfgcBasic = xfgcBasicService.getRepository().findByFlagAndProjectId(1,p.getId());
            p.setGdyBasic(gdyBasic);
            p.setXfgcBasic(xfgcBasic);
        }
        Result result1 = new Result();
        result1.setData(list);
        result1.setCode(result.getCode());
        result1.setMessage(result.getMessage());
        result1.setPage(result.getPage());
        result1.setTotalElements(result.getTotalElements());
        result1.setTotalPage(result.getTotalPage());
        result1.setException(result.exception);
        return result1;
    }



}

